import time,random
import hashlib
import requests
import json

class Youdao():
    '''有道翻译js破解'''
    def Get_salt(self):
        salt = int(time.time() * 1000) + random.randint(0,10)     #  时间戳  毫秒级
        # print(salt)
        return salt


    def Get_md5(slef,a):    #         a = 我们要加密的值
        ''' md5  加密方式'''
        hash = hashlib.md5()
        hash.update(a.encode('utf-8'))
        data = hash.hexdigest()
        return data

    def Get_sign(self,e,salt):        #  i = salt        e 是我们自己翻译的值
        sign = "fanyideskweb" + e + str(salt) + "n%A-rKaT5fb[Gy?;N5@Tj"
        new_sign = self.Get_md5(sign)
        return new_sign

    def Get_post(self,value):
        url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

        salt = self.Get_salt()
        sign = self.Get_sign(value,salt)
        # print(sign)

        data = {
            'i':value,
            'from':'AUTO',
            'to':'AUTO',
            'smartresult':'dict',
            'client':'fanyideskweb',
            'salt':salt,
            'sign':sign,
            'ts':int(time.time() * 1000),
            'bv':'b4cf244dcaabcc8b2ae8b3c5559d3dd6',
            'doctype':'json',
            'version':'2.1',
            'keyfrom':'fanyi.web',
            'action':'FY_BY_REALTlME',
        }

        headers = {
            'Accept':'application/json,text/javascript,*/*;q = 0.01',
            'Accept-Encoding':'gzip,deflate',
            'Accept-Language':'zh-CN,zh;q = 0.9',
            'Cache-Control':'no-cache',
            'Connection':'keep-alive',
            'Content-Length':str(len(value)),
            'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8',
            'Cookie':'OUTFOX_SEARCH_USER_ID=1977534197@119.147.183.51;OUTFOX_SEARCH_USER_ID_NCOO=2025435659.926183;_ntes_nnid=2d97564443721e01660439efc5ee0e83,1568251179503;_ga=GA1.2.1153174907.1569231445;_gid=GA1.2.81649651.1569657154; _gat=1;___rl__test__cookies=1569657169457',
            'Host':'fanyi.youdao.com',
            'Origin':'http://fanyi.youdao.com',
            'Pragma':'no-cache',
            'Referer':'http://fanyi.youdao.com /',
            'User-Agent':'Mozilla/5.0(WindowsNT6.1;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/77.0.3865.90Safari/537.36',
            'X-Requested-With':'XMLHttpRequest',
        }


        res = requests.post(url=url,data=data,headers=headers)
        data = res.content.decode('utf-8')
        #  {"translateResult":[[{"tgt":"悲伤的","src":"sad"}]],"errorCode":0,"type":"en2zh-CHS","smartResult":{"entries":["","adj. 难过的；悲哀的，令人悲痛的；凄惨的，阴郁的（形容颜色）\r\n"],"type":1}}
        myjson = json.loads(data).get('translateResult')[0][0]  # 把json转字典
        item = dict()
        item['翻译的单词'] = myjson.get('tgt')
        item['输入的单词'] = myjson.get('src')
        print(item)

if __name__ == '__main__':
    while True:
        value = input('请输入你要翻译的单词:')
        if value == 'q':
            break
        yd = Youdao()
        yd.Get_post(value)